import axios from 'axios'
import { ElMessage } from 'element-plus'

// 是否使用模拟数据（当后端服务不可用时）
const useMockData = false

// 模拟数据库 - 订单数据
const mockOrders = [
  {
    id: 1001,
    number: 'P202505200001',
    status: 3, // 已接单
    payStatus: 1, // 已支付
    orderTime: '2025-05-20 12:30:45',
    payMethod: 1,
    amount: 128.00,
    remark: '',
    phone: '13800138001',
    address: '北京市朝阳区某小区1号楼2单元303',
    consignee: '张三',
    cancelReason: null,
    rejectionReason: null,
    deliveryStatus: 1,
    deliveryTime: null,
    orderDetailList: [
      {
        id: 10001,
        name: '宫保鸡丁',
        image: 'https://via.placeholder.com/150',
        orderid: 1001,
        number: 2,
        amount: 76.00
      },
      {
        id: 10002,
        name: '蒜蓉炒西兰花',
        image: 'https://via.placeholder.com/150',
        orderid: 1001,
        number: 1,
        amount: 22.00
      },
      {
        id: 10003,
        name: '米饭',
        image: 'https://via.placeholder.com/150',
        orderid: 1001,
        number: 3,
        amount: 30.00
      }
    ]
  },
  {
    id: 1002,
    number: 'P202505200002',
    status: 2, // 待接单
    payStatus: 1, // 已支付
    orderTime: '2025-05-20 13:15:22',
    payMethod: 1,
    amount: 88.00,
    remark: '不要辣',
    phone: '13800138002',
    address: '北京市海淀区某小区5号楼1单元101',
    consignee: '李四',
    cancelReason: null,
    rejectionReason: null,
    deliveryStatus: 0,
    deliveryTime: null,
    orderDetailList: [
      {
        id: 10004,
        name: '麻婆豆腐',
        image: 'https://via.placeholder.com/150',
        orderid: 1002,
        number: 1,
        amount: 38.00
      },
      {
        id: 10005,
        name: '酸菜鱼',
        image: 'https://via.placeholder.com/150',
        orderid: 1002,
        number: 1,
        amount: 50.00
      }
    ]
  },
  {
    id: 1003,
    number: 'P202505200003',
    status: 4, // 派送中
    payStatus: 1, // 已支付
    orderTime: '2025-05-20 12:05:33',
    payMethod: 1,
    amount: 168.00,
    remark: '送餐时请电话联系',
    phone: '13800138003',
    address: '北京市西城区某小区2号楼4单元505',
    consignee: '王五',
    cancelReason: null,
    rejectionReason: null,
    deliveryStatus: 1,
    deliveryTime: '2025-05-20 12:30:00',
    orderDetailList: [
      {
        id: 10006,
        name: '北京烤鸭',
        image: 'https://via.placeholder.com/150',
        orderid: 1003,
        number: 1,
        amount: 138.00
      },
      {
        id: 10007,
        name: '米饭',
        image: 'https://via.placeholder.com/150',
        orderid: 1003,
        number: 3,
        amount: 30.00
      }
    ]
  },
  {
    id: 1004,
    number: 'P202505200004',
    status: 5, // 已完成
    payStatus: 1, // 已支付
    orderTime: '2025-05-20 11:23:15',
    payMethod: 1,
    amount: 92.00,
    remark: '',
    phone: '13800138004',
    address: '北京市东城区某小区3号楼2单元203',
    consignee: '赵六',
    cancelReason: null,
    rejectionReason: null,
    deliveryStatus: 1,
    deliveryTime: '2025-05-20 11:45:00',
    orderDetailList: [
      {
        id: 10008,
        name: '水煮鱼',
        image: 'https://via.placeholder.com/150',
        orderid: 1004,
        number: 1,
        amount: 58.00
      },
      {
        id: 10009,
        name: '炝炒土豆丝',
        image: 'https://via.placeholder.com/150',
        orderid: 1004,
        number: 1,
        amount: 24.00
      },
      {
        id: 10010,
        name: '米饭',
        image: 'https://via.placeholder.com/150',
        orderid: 1004,
        number: 1,
        amount: 10.00
      }
    ]
  },
  {
    id: 1005,
    number: 'P202505200005',
    status: 6, // 已取消
    payStatus: 0, // 未支付
    orderTime: '2025-05-20 10:30:08',
    payMethod: 0,
    amount: 58.00,
    remark: '',
    phone: '13800138005',
    address: '北京市丰台区某小区8号楼5单元702',
    consignee: '孙七',
    cancelReason: '顾客自己取消',
    rejectionReason: null,
    deliveryStatus: 0,
    deliveryTime: null,
    orderDetailList: [
      {
        id: 10011,
        name: '鱼香肉丝',
        image: 'https://via.placeholder.com/150',
        orderid: 1005,
        number: 1,
        amount: 38.00
      },
      {
        id: 10012,
        name: '米饭',
        image: 'https://via.placeholder.com/150',
        orderid: 1005,
        number: 2,
        amount: 20.00
      }
    ]
  }
]

// 模拟数据库 - 员工数据
const mockEmployees = [
  {
    id: 1,
    name: '张三',
    username: 'zhangsan',
    phone: '13800138001',
    sex: 1,
    idNumber: '110101199001010001',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 2,
    name: '李四',
    username: 'lisi',
    phone: '13800138002',
    sex: 1,
    idNumber: '110101199001010002',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 3,
    name: '王五',
    username: 'wangwu',
    phone: '13800138003',
    sex: 0,
    idNumber: '110101199001010003',
    status: 0,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 4,
    name: '赵六',
    username: 'zhaoliu',
    phone: '13800138004',
    sex: 1,
    idNumber: '110101199001010004',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 5,
    name: '孙七',
    username: 'sunqi',
    phone: '13800138005',
    sex: 0,
    idNumber: '110101199001010005',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  }
]

// 模拟数据库 - 菜品分类
const mockCategories = [
  {
    id: 1,
    name: '家常菜',
    type: 1,
    sort: 1,
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 2,
    name: '特色菜',
    type: 1,
    sort: 2,
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 3,
    name: '主食',
    type: 1,
    sort: 3,
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 4,
    name: '热销套餐',
    type: 2,
    sort: 1,
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 5,
    name: '超值套餐',
    type: 2,
    sort: 2,
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  }
]

// 模拟数据库 - 菜品
const mockDishes = [
  {
    id: 1,
    name: '宫保鸡丁',
    categoryId: 1,
    price: 38.00,
    image: 'https://via.placeholder.com/150',
    description: '宫保鸡丁，是一道闻名中外的特色传统名菜',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 2,
    name: '麻婆豆腐',
    categoryId: 1,
    price: 38.00,
    image: 'https://via.placeholder.com/150',
    description: '麻婆豆腐，是四川省传统名菜之一',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 3,
    name: '北京烤鸭',
    categoryId: 2,
    price: 138.00,
    image: 'https://via.placeholder.com/150',
    description: '北京烤鸭是北京最著名的菜式之一',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  },
  {
    id: 4,
    name: '米饭',
    categoryId: 3,
    price: 10.00,
    image: 'https://via.placeholder.com/150',
    description: '香喷喷的米饭',
    status: 1,
    updateTime: '2023-05-14 19:27:41'
  }
]

// 模拟数据库 - 套餐
const mockSetmeals = [
  {
    id: 1,
    name: '商务套餐A',
    categoryId: 4,
    price: 128.00,
    image: 'https://via.placeholder.com/150',
    description: '适合3-4人的商务套餐',
    status: 1,
    updateTime: '2023-05-14 19:27:41',
    dishList: [
      {
        id: 1,
        name: '宫保鸡丁',
        copies: 1
      },
      {
        id: 2,
        name: '麻婆豆腐',
        copies: 1
      },
      {
        id: 4,
        name: '米饭',
        copies: 4
      }
    ]
  },
  {
    id: 2,
    name: '家庭套餐B',
    categoryId: 5,
    price: 178.00,
    image: 'https://via.placeholder.com/150',
    description: '适合4-6人的家庭套餐',
    status: 1,
    updateTime: '2023-05-14 19:27:41',
    dishList: [
      {
        id: 1,
        name: '宫保鸡丁',
        copies: 1
      },
      {
        id: 2,
        name: '麻婆豆腐',
        copies: 1
      },
      {
        id: 3,
        name: '北京烤鸭',
        copies: 1
      },
      {
        id: 4,
        name: '米饭',
        copies: 6
      }
    ]
  }
]

// 订单状态统计数据
const mockOrderStatistics = {
  toBeConfirmed: 1,    // 待接单数量  
  confirmed: 1,        // 待派送数量
  deliveryInProgress: 1 // 派送中数量
}

// 工作台 - 今日运营数据
const mockBusinessData = {
  turnover: 12580.50,           // 营业额
  validOrderCount: 25,          // 有效订单数
  orderCompletionRate: 85.6,    // 订单完成率
  unitPrice: 503.22,            // 平均客单价
  newUsers: 8                   // 新增用户数
}

// 工作台 - 订单管理概览
const mockOrderOverview = {
  waitingOrders: 3,       // 待接单
  deliveredOrders: 2,     // 待派送  
  completedOrders: 15,    // 已完成
  cancelledOrders: 2,     // 已取消
  allOrders: 22          // 全部订单
}

// 工作台 - 菜品总览
const mockDishOverview = {
  sold: 12,              // 已启售菜品数量
  discontinued: 3        // 已停售菜品数量
}

// 工作台 - 套餐总览
const mockSetmealOverview = {
  sold: 8,               // 已启售套餐数量
  discontinued: 1        // 已停售套餐数量
}

// 创建axios实例，配置baseURL为8080端口
const api = axios.create({
  baseURL: '/api',  // 使用相对路径，由Vite代理转发
  timeout: 5000
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    console.log('发送请求:', config.method, config.url, config.data || config.params)
    
    // 非登录请求添加token
    if (!config.url.includes('/admin/employee/login')) {
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.token = token
      }
    }
    
    // 设置Content-Type
    if (config.method === 'post' || config.method === 'put') {
      config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/json;charset=UTF-8'
    }
    
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('响应成功:', response.config.url, response.data)
    
    if (response.config.url.includes('/admin/employee/login')) {
      return response
    }
    
    // 处理正常响应
    const { code, data, msg } = response.data
    
    if (code === 1 || code === 0 || code === 200) {
      // 直接返回原始响应，让组件自行处理数据
      return response
    }
    
    ElMessage.error(msg || '请求失败')
    return Promise.reject(new Error(msg || '请求失败'))
  },
  error => {
    console.error('响应错误:', error.message)
    
    // 模拟数据处理
    if (useMockData && error.config) {
      console.warn('API请求失败，使用模拟数据')
      return handleMockResponse(error.config)
    }
    
    // 401处理
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    
    const errorMsg = error.response?.data?.msg || error.message || '网络请求失败'
    ElMessage.error(errorMsg)
    return Promise.reject(error)
  }
)

// 模拟响应处理函数
function handleMockResponse(config) {
  const { url, method, params, data } = config
  let responseData
  
  console.log('生成模拟响应:', url, method, params)
  
  // 根据URL返回相应的模拟数据
  if (url.includes('/admin/order/statistics')) {
    responseData = { code: 1, msg: 'success', data: mockOrderStatistics }
  } 
  else if (url.includes('/admin/order/conditionSearch')) {
    // 过滤和分页订单
    let filteredOrders = [...mockOrders]
    
    if (params?.status) {
      filteredOrders = filteredOrders.filter(order => order.status.toString() === params.status.toString())
    }
    if (params?.number) {
      filteredOrders = filteredOrders.filter(order => order.number.includes(params.number))
    }
    if (params?.phone) {
      filteredOrders = filteredOrders.filter(order => order.phone.includes(params.phone))
    }
    
    // 分页
    const page = params?.page || 1
    const pageSize = params?.pageSize || 10
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const records = filteredOrders.slice(start, end)
    
    responseData = {
      code: 1,
      msg: 'success',
      data: {
        records: records,
        total: filteredOrders.length,
        pages: Math.ceil(filteredOrders.length / pageSize),
        page: Number(page),
        pageSize: Number(pageSize)
      }
    }
  } 
  else if (url.includes('/admin/order/details/')) {
    const orderId = url.split('/').pop()
    const order = mockOrders.find(o => o.id.toString() === orderId || o.number === orderId)
    responseData = order ? 
      { code: 1, msg: 'success', data: order } : 
      { code: 0, msg: '订单不存在', data: null }
  }
  else if (url.includes('/admin/employee/page')) {
    const page = params?.page || 1
    const pageSize = params?.pageSize || 10
    const name = params?.name || ''
    
    let filteredEmployees = mockEmployees
    if (name) {
      filteredEmployees = mockEmployees.filter(emp => emp.name.includes(name))
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const records = filteredEmployees.slice(start, end)
    
    responseData = {
      code: 1,
      msg: 'success',
      data: {
        records: records,
        total: filteredEmployees.length,
        pages: Math.ceil(filteredEmployees.length / pageSize),
        size: Number(pageSize),
        current: Number(page),
        searchCount: true,
        orders: []
      }
    }
  }
  else if (url.includes('/admin/category/page')) {
    const page = params?.page || 1
    const pageSize = params?.pageSize || 10
    const name = params?.name || ''
    const type = params?.type
    
    let filteredCategories = mockCategories
    if (name) {
      filteredCategories = filteredCategories.filter(cat => cat.name.includes(name))
    }
    if (type) {
      filteredCategories = filteredCategories.filter(cat => cat.type.toString() === type.toString())
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const records = filteredCategories.slice(start, end)
    
    responseData = {
      code: 1,
      msg: 'success',
      data: {
        records: records,
        total: filteredCategories.length,
        pages: Math.ceil(filteredCategories.length / pageSize),
        size: Number(pageSize),
        current: Number(page),
        searchCount: true,
        orders: []
      }
    }
  }
  else if (url.includes('/admin/category/list')) {
    let filteredCategories = mockCategories
    if (params && params.type) {
      filteredCategories = filteredCategories.filter(cat => cat.type.toString() === params.type.toString())
    }
    
    responseData = {
      code: 1,
      msg: 'success',
      data: filteredCategories
    }
  }
  else if (url.includes('/admin/dish/page')) {
    const page = params?.page || 1
    const pageSize = params?.pageSize || 10
    const name = params?.name || ''
    const categoryId = params?.categoryId
    
    let filteredDishes = mockDishes
    if (name) {
      filteredDishes = filteredDishes.filter(dish => dish.name.includes(name))
    }
    if (categoryId) {
      filteredDishes = filteredDishes.filter(dish => dish.categoryId.toString() === categoryId.toString())
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const records = filteredDishes.slice(start, end)
    
    responseData = {
      code: 1,
      msg: 'success',
      data: {
        records: records,
        total: filteredDishes.length,
        pages: Math.ceil(filteredDishes.length / pageSize),
        size: Number(pageSize),
        current: Number(page),
        searchCount: true,
        orders: []
      }
    }
  }
  else if (url.includes('/admin/setmeal/page')) {
    const page = params?.page || 1
    const pageSize = params?.pageSize || 10
    const name = params?.name || ''
    const categoryId = params?.categoryId
    
    let filteredSetmeals = mockSetmeals
    if (name) {
      filteredSetmeals = filteredSetmeals.filter(setmeal => setmeal.name.includes(name))
    }
    if (categoryId) {
      filteredSetmeals = filteredSetmeals.filter(setmeal => setmeal.categoryId.toString() === categoryId.toString())
    }
    
    const start = (page - 1) * pageSize
    const end = start + pageSize
    const records = filteredSetmeals.slice(start, end)
    
    responseData = {
      code: 1,
      msg: 'success',
      data: {
        records: records,
        total: filteredSetmeals.length,
        pages: Math.ceil(filteredSetmeals.length / pageSize),
        size: Number(pageSize),
        current: Number(page),
        searchCount: true,
        orders: []
      }
    }
  }
  // 工作台接口处理
  else if (url.includes('/admin/workspace/businessData')) {
    responseData = { code: 1, msg: 'success', data: mockBusinessData }
  }
  else if (url.includes('/admin/workspace/overviewOrders')) {
    responseData = { code: 1, msg: 'success', data: mockOrderOverview }
  }
  else if (url.includes('/admin/workspace/overviewDishes')) {
    responseData = { code: 1, msg: 'success', data: mockDishOverview }
  }
  else if (url.includes('/admin/workspace/overviewSetmeals')) {
    responseData = { code: 1, msg: 'success', data: mockSetmealOverview }
  }
  else {
    responseData = {
      code: 1,
      msg: 'success',
      data: null
    }
  }
  
  return Promise.resolve({ 
    data: responseData
  })
}

// 模拟响应工具函数
const mockResponse = (data, delay = 300) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({ data: { code: 1, msg: 'success', data } })
    }, delay)
  })
}

// ====================== API接口定义 ======================

// 分类相关接口
export const categoryApi = {
  // 分类分页查询
  page(params) {
    return api.get('/admin/category/page', { params })
  },
  
  // 根据类型查询分类
  list(params) {
    return api.get('/admin/category/list', { params })
  },
  
  // 新增分类
  add(data) {
    return api.post('/admin/category', data)
  },
  
  // 修改分类
  update(data) {
    return api.put('/admin/category', data)
  },
  
  // 根据id删除分类
  delete(id) {
    return api.delete('/admin/category', { params: { id } })
  },
  
  // 启用、禁用分类
  updateStatus(id, status) {
    return api.post(`/admin/category/status/${status}`, null, { params: { id } })
  }
}

// 菜品相关接口
export const dishApi = {
  // 菜品分页查询
  page(params) {
    return api.get('/admin/dish/page', { params })
  },
  
  // 根据分类id查询菜品
  list(params) {
    return api.get('/admin/dish/list', { params })
  },
  
  // 根据id查询菜品
  getById(id) {
    return api.get(`/admin/dish/${id}`)
  },
  
  // 新增菜品
  add(data) {
    return api.post('/admin/dish', data)
  },
  
  // 修改菜品
  update(data) {
    return api.put('/admin/dish', data)
  },
  
  // 批量删除菜品
  batchDelete(ids) {
    return api.delete('/admin/dish', { params: { ids: ids.join(',') } })
  },
  
  // 菜品起售、停售
  updateStatus(id, status) {
    return api.post(`/admin/dish/status/${status}`, null, { params: { id } })
  }
}

// 套餐相关接口
export const setmealApi = {
  // 分页查询
  page(params) {
    return api.get('/admin/setmeal/page', { params })
  },
  
  // 根据id查询套餐信息
  getById(id) {
    return api.get(`/admin/setmeal/${id}`)
  },
  
  // 新增套餐
  add(data) {
    return api.post('/admin/setmeal', data)
  },
  
  // 修改套餐
  update(data) {
    return api.put('/admin/setmeal', data)
  },
  
  // 批量删除套餐
  batchDelete(ids) {
    return api.delete('/admin/setmeal', { params: { ids: ids.join(',') } })
  },
  
  // 套餐起售、停售
  updateStatus(id, status) {
    return api.post(`/admin/setmeal/status/${status}`, null, { params: { id } })
  }
}

// 员工相关接口
export const employeeApi = {
  // 员工登录
  login(data) {
    if (useMockData) {
      if (data.username === 'admin' && data.password === '123456') {
        return mockResponse({
          token: 'mock-token-12345',
          userInfo: { id: 1, name: '管理员', username: 'admin' }
        })
      } else {
        return Promise.reject(new Error('用户名或密码错误'))
      }
    }
    return api.post('/admin/employee/login', data)
  },
  
  // 退出登录
  logout() {
    return api.post('/admin/employee/logout')
  },
  
  // 员工分页查询
  list(params) {
    return api.get('/admin/employee/page', { params })
  },
  
  // 根据id查询员工
  getById(id) {
    return api.get(`/admin/employee/${id}`)
  },
  
  // 新增员工
  create(data) {
    return api.post('/admin/employee', data)
  },
  
  // 编辑员工信息
  update(data) {
    return api.put('/admin/employee', data)
  },
  
  // 启用、禁用员工账号
  updateStatus(id, status) {
    return api.post(`/admin/employee/status/${status}`, null, { params: { id } })
  },
  
  // 修改密码
  updatePassword(data) {
    return api.put('/admin/employee/editPassword', data)
  }
}

// 订单相关接口
export const orderApi = {
  // 订单搜索
  conditionSearch(params) {
    return api.get('/admin/order/conditionSearch', { params })
  },
  
  // 查询订单详情
  details(id) {
    return api.get(`/admin/order/details/${id}`)
  },
  
  // 各个状态的订单数量统计
  statistics() {
    return api.get('/admin/order/statistics')
  },
  
  // 接单
  confirm(data) {
    return api.put('/admin/order/confirm', data)
  },
  
  // 拒单
  rejection(data) {
    return api.put('/admin/order/rejection', data)
  },
  
  // 取消订单
  cancel(data) {
    return api.put('/admin/order/cancel', data)
  },
  
  // 派送订单
  delivery(id) {
    return api.put(`/admin/order/delivery/${id}`)
  },
  
  // 完成订单
  complete(id) {
    return api.put(`/admin/order/complete/${id}`)
  },
  
  // 获取订单统计数据
  getOrderStatistics() {
    return this.statistics()
  }
}

// 店铺操作接口
export const shopApi = {
  // 获取营业状态
  getStatus() {
    return api.get('/admin/shop/status')
  },
  
  // 设置营业状态
  setStatus(status) {
    // 确保status是整数
    const statusValue = parseInt(status) || 0
    return api.put(`/admin/shop/${statusValue}`)
  }
}

// 文件上传接口
export const uploadApi = {
  // 文件上传
  upload(file) {
    const formData = new FormData()
    formData.append('file', file)
    
    return api.post('/admin/common/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
  }
}

// 工作台接口
export const workspaceApi = {
  // 查询今日运营数据
  businessData() {
    return api.get('/admin/workspace/businessData')
  },

  // 查询订单管理数据
  overviewOrders() {
    return api.get('/admin/workspace/overviewOrders')
  },

  // 查询菜品总览
  overviewDishes() {
    return api.get('/admin/workspace/overviewDishes')
  },

  // 查询套餐总览
  overviewSetmeals() {
    return api.get('/admin/workspace/overviewSetmeals')
  }
}

// 催单提醒功能
export const reminderApi = {
  // 催单
  reminder(orderId) {
    return api.get(`/user/order/reminder/${orderId}`)
  }
}

export default api 